package com.dev.dream.exochatlockscreen;

import java.util.ArrayList;

import uk.co.chrisjenx.calligraphy.CalligraphyConfig;
import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.dev.dream.exochatlockscreen.service.SLockscreen;
import com.dev.dream.exochatlockscreen.slidemenu.HelpFragment;
import com.dev.dream.exochatlockscreen.slidemenu.HomeFragment;
import com.dev.dream.exochatlockscreen.slidemenu.SettingsFragment;
import com.dev.dream.exochatlockscreen.slidemenu.SettingsReceiveMsgFragment;
import com.dev.dream.exochatlockscreen.slidemenu.SettingsSendMsgFragment;
import com.dev.dream.libs.checknetwork.CheckNetword;
import com.dev.dream.libs.listviewanimation.simple.SwingLeftInAnimationAdapter;
import com.dev.dream.libs.share.MyShare;
import com.dev.dream.libs.slidemenu.adapter.NavDrawerListAdapter;
import com.dev.dream.libs.slidemenu.model.NavDrawerItem;
import com.startapp.android.publish.StartAppAd;
import com.startapp.android.publish.StartAppSDK;

@SuppressLint("NewApi")
public class MainActivity extends Activity {
	private static boolean show_menu;
	private DrawerLayout mDrawerLayout;
	private ListView mDrawerList;
	private ActionBarDrawerToggle mDrawerToggle;

	// nav drawer title
	private CharSequence mDrawerTitle;

	// used to store app title
	private CharSequence mTitle;

	// slide menu items
	private String[] navMenuTitles;
	private TypedArray navMenuIcons;

	private ArrayList<NavDrawerItem> navDrawerItems;
	private NavDrawerListAdapter adapter;
	int width, height;

	private SharedPreferences pre;
	private StartAppAd startAppAd;

	Handler handler_timer = new Handler();

	public Runnable update_time = new Runnable() {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			// time++;
			// if (time > timeDelay) {
			startAppAd.show();
			startAppAd.load();
			// time = 0;
			// }
			// Log.d("kai", "chay");
			handler_timer.postDelayed(update_time, 1000 * 80);
		}
	};

	// Handler handlerUpdateService = new Handler();
	// Runnable update = new Runnable() {
	//
	// @Override
	// public void run() {
	// // TODO Auto-generated method stub
	//
	// System.out.println("check");
	//
	// handlerUpdateService.postDelayed(update, 1000);
	// }
	// };

	SwingLeftInAnimationAdapter swingLeftInAnimationAdapter;
	BroadcastReceiver mReceiver;

	@Override
	protected void attachBaseContext(Context newBase) {
		super.attachBaseContext(new CalligraphyContextWrapper(newBase));
	}

	String click_ad1 = "ad1_20102014";
	String click_ad2 = "ad2_20102014";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		CalligraphyConfig.initDefault("fonts/ttt.ttf", R.attr.fontPath);

		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

		setContentView(R.layout.activity_main);

		// Uri uriSMSURI = Uri.parse("content://sms/inbox");
		// Cursor mCursor = getContentResolver().query(uriSMSURI, null, null,
		// null, null);
		// for (int i = 0; i < mCursor.getColumnCount(); i++) {
		// Log.d("Kai", "Column: " + mCursor.getColumnName(i)+ "   " + "\n");
		//
		// }
		// handlerUpdateService.postDelayed(update, 1000);

		pre = getSharedPreferences("com.dev.dream.exochatlockscreen.ads",
				MODE_PRIVATE);

		StartAppSDK.init(this, "111076217 ", "210808285", true);
		startAppAd.showSplash(this, savedInstanceState);
		StartAppAd.showSlider(this);
		startAppAd = new StartAppAd(this);

		EXOChatKeypadPreferences.getInstance().initPreferences(this);

		//if (EXOChatKeypadPreferences.getInstance().isEnableLockscreen()) {
			if (SLockscreen.instance == null) {

				startService(new Intent(getApplicationContext(),
						SLockscreen.class));

			}
		//}
		
		

		if (CheckNetword.checkInternetConnection(getApplicationContext())) {
			handler_timer.postDelayed(update_time, 1000 * 20);
		}
		// IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
		// filter.addAction(Intent.ACTION_SCREEN_OFF);
		//
		// mReceiver = new LockScreenReeiver();
		// registerReceiver(mReceiver, filter);

		DisplayMetrics displaymetrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
		height = displaymetrics.heightPixels;
		width = displaymetrics.widthPixels;

		mTitle = mDrawerTitle = getTitle();

		// load slide menu items
		navMenuTitles = getResources().getStringArray(R.array.nav_drawer_title);

		// nav drawer icons from resources
		navMenuIcons = getResources()
				.obtainTypedArray(R.array.nav_drawer_icons);

		mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

		mDrawerList = (ListView) findViewById(R.id.list_slidermenu);

		navDrawerItems = new ArrayList<NavDrawerItem>();

		// adding nav drawer items to array
		// Home
		navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons
				.getResourceId(0, -1)));
		// Find People
		navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons
				.getResourceId(1, -1), true, EXOChatKeypadPreferences
				.getInstance().size_bg + ""));
		// Photos
		navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons
				.getResourceId(2, -1)));
		// Communities, Will add a counter here
		navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons
				.getResourceId(3, -1)));
		// Pages
		navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons
				.getResourceId(4, -1)));
		// What's hot, We will add a counter here
		navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons
				.getResourceId(5, -1)));

		navDrawerItems.add(new NavDrawerItem(navMenuTitles[6], navMenuIcons
				.getResourceId(6, -1)));
		navDrawerItems.add(new NavDrawerItem(navMenuTitles[7], navMenuIcons
				.getResourceId(7, -1)));
		navDrawerItems.add(new NavDrawerItem(navMenuTitles[8], navMenuIcons
				.getResourceId(8, -1)));
		navDrawerItems.add(new NavDrawerItem(navMenuTitles[9], navMenuIcons
				.getResourceId(9, -1)));

		// Recycle the typed array
		navMenuIcons.recycle();

		mDrawerList.setOnItemClickListener(new SlideMenuClickListener());

		// setting the nav drawer list adapter
		adapter = new NavDrawerListAdapter(getApplicationContext(),
				navDrawerItems);

		// mDrawerList.setAdapter(adapter);

		// enabling action bar app icon and behaving it as toggle button
		getActionBar().setDisplayHomeAsUpEnabled(true);
		getActionBar().setHomeButtonEnabled(true);

		mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
				R.drawable.ic_topbar_nav_menu, // nav menu toggle icon
				R.string.app_name, // nav drawer open - description for
									// accessibility
				R.string.app_name // nav drawer close - description for
									// accessibility
		) {
			public void onDrawerClosed(View view) {
				getActionBar().setTitle(mTitle);
				// calling onPrepareOptionsMenu() to show action bar icons
				invalidateOptionsMenu();
			}

			public void onDrawerOpened(View drawerView) {
				getActionBar().setTitle(mDrawerTitle);
				// calling onPrepareOptionsMenu() to hide action bar icons
				if (!show_menu) {
					show_menu = true;
					swingLeftInAnimationAdapter = new SwingLeftInAnimationAdapter(
							adapter);
					swingLeftInAnimationAdapter.setAbsListView(mDrawerList);
					mDrawerList.setAdapter(swingLeftInAnimationAdapter);
				}
				invalidateOptionsMenu();
			}
		};
		mDrawerLayout.setDrawerListener(mDrawerToggle);

		if (savedInstanceState == null) {
			// on first time display view for first nav item
			displayView(0);
		}
	}

	// Handler handler_timer = new Handler();
	// int time = 60 * 3, timeDelay = 60;
	//
	// public Runnable update_time = new Runnable() {
	//
	// @Override
	// public void run() {
	// // TODO Auto-generated method stub
	// time++;
	//
	//
	// // System.out.println(time);
	// handler_timer.postDelayed(update_time, 1000);
	// }
	// };

	@Override
	public void onAttachedToWindow() {
		// TODO Auto-generated method stub
		super.onAttachedToWindow();

		if (CheckNetword.checkInternetConnection(getApplicationContext())) {
			if (!pre.getBoolean(click_ad1, false)) {

				showPopup(this);

			}

			// if (pre.getBoolean(click_ad1, false)) {
			//
			// if (!pre.getBoolean(click_ad2, false)) {
			// if (savedInstanceState == null) {
			// layout.post(new Runnable() {
			// @Override
			// public void run() {
			// showPopup2(MainActivity.this);
			//
			// }
			// });
			// }
			//
			// }
			// }
		}

		if (!EXOChatKeypadPreferences.getInstance().isShowGuid()) {
			showPopupGuide(this);
		}
	}

	/**
	 * Slide menu item click listener
	 * */
	private class SlideMenuClickListener implements
			ListView.OnItemClickListener {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			// display view for selected nav drawer item

			displayView(position);

			// kai

		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// toggle nav drawer on selecting action bar app icon/title
		if (mDrawerToggle.onOptionsItemSelected(item)) {
			return true;
		}
		// Handle action bar actions click
		switch (item.getItemId()) {
		case R.id.action_settings:
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	/* *
	 * Called when invalidateOptionsMenu() is triggered
	 */
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		// if nav drawer is opened, hide the action items
		boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
		menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
		return super.onPrepareOptionsMenu(menu);
	}

	/**
	 * Diplaying fragment view for selected nav drawer list item
	 * */
	private void displayView(int position) {
		// update the main content by replacing fragments
//		Fragment fragment = null;
//		switch (position) {
//		case 0:
//			fragment = new HomeFragment();
//			
//			break;
//		case 1:
//			// fragment = new IconThemeFragment();
//			fragment = new SettingsFragment();
//			
//			break;
//		case 2:
//			// fragment = new IconThemeFragment();
//			fragment = new SettingsReceiveMsgFragment();
//			
//			break;
//		case 3:
//			fragment = new SettingsSendMsgFragment();
//			
//			break;
//		case 4:
//			fragment = new HelpFragment();
//			
//			break;
//		case 5:
//			Intent intent_more = new Intent(Intent.ACTION_VIEW,
//					Uri.parse(getString(R.string.url_more)));
//			startActivity(intent_more);
//			
//			break;
//		case 6:
//
//			Intent intent_rate = new Intent(
//					Intent.ACTION_VIEW,
//					Uri.parse("https://play.google.com/store/apps/details?id=com.dev.dream.apps.keypadlockscreen"));
//			startActivity(intent_rate);
//			
//			
//			break;
//
//		case 7:
//			Intent emailIntent = new Intent(Intent.ACTION_SENDTO,
//					Uri.fromParts("mailto", "iapp.ptit@gmail.com", null));
//			emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
//					getString(R.string.subject_email));
//
//			startActivity(Intent.createChooser(emailIntent, ""));
//			// fragment = new WhatsHotFragment();
//			
//			break;
//		case 8:
//			MyShare.shareTextUrl(MainActivity.this,
//					getString(R.string.message_share),
//					getString(R.string.subject_share));
//			
//			
//
//			break;
//		case 9:
//			Intent viewIntent = new Intent("android.intent.action.VIEW",
//					Uri.parse("https://www.facebook.com/EXOKpopEnt"));
//			startActivity(viewIntent);
//			break;
//
//		default:
//			break;
//		}
//
//		if (fragment != null) {
//			FragmentManager fragmentManager = getFragmentManager();
//			fragmentManager.beginTransaction()
//					.replace(R.id.frame_container, fragment).commit();
//
//			// update selected item and title, then close the drawer
//			mDrawerList.setItemChecked(position, true);
//			mDrawerList.setSelection(position);
//			setTitle(navMenuTitles[position]);
//			mDrawerLayout.closeDrawer(mDrawerList);
//		} else {
//			// error in creating fragment
//			Log.e("MainActivity", "Error in creating fragment");
//		}
	}

	@Override
	public void setTitle(CharSequence title) {
		mTitle = title;
		getActionBar().setTitle(mTitle);
	}

	/**
	 * When using the ActionBarDrawerToggle, you must call it during
	 * onPostCreate() and onConfigurationChanged()...
	 */

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		// Sync the toggle state after onRestoreInstanceState has occurred.
		mDrawerToggle.syncState();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		// Pass any configuration change to the drawer toggls
		mDrawerToggle.onConfigurationChanged(newConfig);
	}

	private void showPopupGuide(final Activity context) {

		// getApplicationContext());

		// Inflate the popup_layout.xml
		RelativeLayout viewGroup = (RelativeLayout) context
				.findViewById(R.id.ll_popup_help);

		LayoutInflater layoutInflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		View layout = layoutInflater.inflate(R.layout.popup_help, viewGroup);

		ImageView slidingimage = (ImageView) layout
				.findViewById(R.id.img_guide);

		// Creating the PopupWindow
		final PopupWindow popup = new PopupWindow(context);
		popup.setContentView(layout);
		popup.setWidth(width);
		popup.setHeight(height);
		popup.setTouchable(true);
		popup.setFocusable(false);
		popup.setOutsideTouchable(false);
		popup.setAnimationStyle(R.style.PopupWindowAnimation);

		// Some offset to align the popup a bit to the right, and a bit down,
		// relative to button's position.
		int OFFSET_X = 30;
		int OFFSET_Y = 30;

		// Clear the default translucent background
		popup.setBackgroundDrawable(new BitmapDrawable());

		// Displaying the popup at the specified location, + offsets.
		popup.showAtLocation(layout, Gravity.CENTER, 0, 0);

		// Getting a reference to Close button, and close the popup when
		// clicked.

		// slidingimage.setOnClickListener(new OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		// // TODO Auto-generated method stub
		// // Toast.makeText(getApplicationContext(), "Click",
		// // 1000).show();
		//
		// popup.dismiss();
		// }
		// });

		ImageView img_gotit = (ImageView) layout.findViewById(R.id.img_got_it);
		img_gotit.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				EXOChatKeypadPreferences.getInstance().setShowGuid(true);
				popup.dismiss();
			}
		});

		// videoview.start();

	}

	boolean doubleBackToExitPressedOnce, isShow, askDownload;

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub

		if (doubleBackToExitPressedOnce) {

			handler_timer.removeCallbacks(update_time);

			if (CheckNetword.checkInternetConnection(getApplicationContext())) {
				if (!isShow) {

					isShow = true;
					// Toast.makeText(getApplicationContext(), "show popup",
					// 1000).show();
					showPopupExit(this);

				}
				//
			} else {

				finish();
			}

		}

		this.doubleBackToExitPressedOnce = true;

		Toast.makeText(this, "Please click BACK again to exit",
				Toast.LENGTH_SHORT).show();

		new Handler().postDelayed(new Runnable() {

			@Override
			public void run() {
				doubleBackToExitPressedOnce = false;

			}
		}, 2000);
	}

	ImageView slidingimage;

	private void showPopupExit(final Activity context) {

		int popupWidth = width * 3 / 4; // (int) convertPixelsToDp(480,
		// getApplicationContext());
		int popupHeight = popupWidth / 3 * 4; // (int) convertPixelsToDp(640,
		// getApplicationContext());

		// Inflate the popup_layout.xml
		RelativeLayout viewGroup = (RelativeLayout) context
				.findViewById(R.id.popup_exit);

		LayoutInflater layoutInflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		View layout = layoutInflater.inflate(R.layout.popup_exit_layout,
				viewGroup);

		slidingimage = (ImageView) layout.findViewById(R.id.imgExit);

		slidingimage.setBackgroundResource(R.drawable.list_animation0);

		AnimationDrawable rocketAnimation = (AnimationDrawable) slidingimage
				.getBackground();
		rocketAnimation.start();

		// Creating the PopupWindow
		final PopupWindow popup = new PopupWindow(context);
		popup.setContentView(layout);
		popup.setWidth(popupWidth);
		popup.setHeight(popupHeight);
		popup.setTouchable(true);
		popup.setFocusable(false);
		popup.setOutsideTouchable(false);
		popup.setAnimationStyle(R.style.PopupWindowAnimation);

		// Some offset to align the popup a bit to the right, and a bit down,
		// relative to button's position.
		int OFFSET_X = 30;
		int OFFSET_Y = 30;

		// Clear the default translucent background
		popup.setBackgroundDrawable(new BitmapDrawable());

		// Displaying the popup at the specified location, + offsets.
		// popup.showAtLocation(layout, Gravity.NO_GRAVITY,
		// (width - popupWidth) / 2, (height - popupHeight) / 2);

		popup.showAtLocation(layout, Gravity.CENTER, 0, 0);

		// Getting a reference to Close button, and close the popup when
		// clicked.

		TextView txt = (TextView) layout.findViewById(R.id.txtAsk);
		txt.setVisibility(View.GONE);

		if (!pre.getBoolean("rate", false)) {

			Button btnNo = (Button) layout.findViewById(R.id.btnNo);
			btnNo.setVisibility(View.GONE);

			Button btnGood = (Button) layout.findViewById(R.id.btnGood);
			btnGood.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					popup.dismiss();

					SharedPreferences.Editor edit = pre.edit();
					edit.putBoolean("rate", true);
					edit.commit();

					Intent i = new Intent(
							Intent.ACTION_VIEW,
							Uri.parse("https://play.google.com/store/apps/details?id=com.dev.dream.exochatlockscreen"));

					startActivity(i);
					finish();
				}
			});

			Button btnBad = (Button) layout.findViewById(R.id.btnBad);
			btnBad.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					popup.dismiss();

					SharedPreferences.Editor edit = pre.edit();
					edit.putBoolean("rate", true);
					edit.commit();

					// Use your own code here
					Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri
							.fromParts("mailto", "iapp.ptit@gmail.com", null));
					emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
							getString(R.string.subject_email));

					startActivity(Intent.createChooser(emailIntent, ""));

					finish();
				}
			});

			Button btnlater = (Button) layout.findViewById(R.id.btnLate);
			btnlater.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					popup.dismiss();
					finish();
				}
			});
		} else {
			Button btnGood = (Button) layout.findViewById(R.id.btnGood);
			btnGood.setVisibility(View.GONE);
			Button btnlater = (Button) layout.findViewById(R.id.btnLate);
			btnlater.setVisibility(View.GONE);
			Button btnBad = (Button) layout.findViewById(R.id.btnBad);
			btnBad.setVisibility(View.GONE);

			Button btnNo = (Button) layout.findViewById(R.id.btnNo);
			btnNo.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					popup.dismiss();

					finish();
				}
			});
		}
		slidingimage.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				// Toast.makeText(getApplicationContext(), "Click",
				// 1000).show();

				Intent i = new Intent(Intent.ACTION_VIEW, Uri
						.parse(getString(R.string.url_more)));
				startActivity(i);

				SharedPreferences.Editor edit = pre.edit();
				edit.putBoolean("click2", true);
				edit.commit();

				// isShow = false;

				// popup.dismiss();
			}
		});

	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		handler_timer.removeCallbacks(update_time);
		show_menu = false;
		super.onDestroy();
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		// handler_timer.removeCallbacks(update_time);
		super.onPause();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		// handler_timer.postDelayed(update_time, 1000 * 50);

		super.onResume();
	}

	private void showPopup(final Activity context) {

		// getApplicationContext());
		
		int popupWidth = width * 3 / 4; // (int) convertPixelsToDp(480,
		int popupHeight = popupWidth * 4 / 3; // (int) convertPixelsToDp(640,

		// Inflate the popup_layout.xml
		RelativeLayout viewGroup = (RelativeLayout) context
				.findViewById(R.id.popup);

		LayoutInflater layoutInflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		View layout = layoutInflater.inflate(R.layout.popup_layout, viewGroup);

		slidingimage = (ImageView) layout.findViewById(R.id.img);

		slidingimage.setBackgroundResource(R.drawable.list_animation);

		AnimationDrawable rocketAnimation = (AnimationDrawable) slidingimage
				.getBackground();
		rocketAnimation.start();

		// Creating the PopupWindow
		final PopupWindow popup = new PopupWindow(context);
		popup.setContentView(layout);
		popup.setWidth(popupWidth);
		popup.setHeight(popupHeight);
		popup.setTouchable(true);
		popup.setFocusable(false);
		popup.setOutsideTouchable(false);
		popup.setAnimationStyle(R.style.PopupWindowAnimation);

		// Some offset to align the popup a bit to the right, and a bit down,
		// relative to button's position.
		int OFFSET_X = 30;
		int OFFSET_Y = 30;

		// Clear the default translucent background
		popup.setBackgroundDrawable(new BitmapDrawable());

		// Displaying the popup at the specified location, + offsets.
		popup.showAtLocation(layout, Gravity.NO_GRAVITY,
				(width - popupWidth) / 2, (height - popupHeight) / 2);

		// Getting a reference to Close button, and close the popup when
		// clicked.

		ImageView close = (ImageView) layout.findViewById(R.id.close);
		close.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				popup.dismiss();
			}
		});

		slidingimage.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				// Toast.makeText(getApplicationContext(), "Click",
				// 1000).show();

				Intent i = new Intent(
						Intent.ACTION_VIEW,
						Uri.parse("https://play.google.com/store/apps/details?id=com.dev.dream.chickenspacewar"));
				startActivity(i);

				SharedPreferences.Editor edit = pre.edit();
				edit.putBoolean(click_ad1, true);
				edit.commit();

				popup.dismiss();
			}
		});

		// videoview.start();

	}

}
